package com.shuoyue.ycgk.net;

import android.text.TextUtils;

import com.google.gson.GsonBuilder;
import com.shuoyue.appdepends.commonutils.XLog;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.MyApplication;
import com.shuoyue.ycgk.appcatch.MemeryCatch;
import com.shuoyue.ycgk.net.gsondefaultadapter.DoubleDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.FloatDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.IntegerDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.LongDefaultAdapter;
import com.shuoyue.ycgk.net.gsondefaultadapter.StringNullAdapter;
import com.shuoyue.ycgk.utils.InterNetUtil;

import java.io.IOException;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {
    /**
     * 服务器地址
     */
  private RetrofitUtil() {

    }

    public static Retrofit getRetrofit() {
        return Instanace.retrofit;
    }

    private static Retrofit getInstanace() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                XLog.i("RxJava", message);
            }
        });
        Interceptor cacheInterceptor = chain -> {
            Request request = chain.request();
            //有网的时候,读接口上的@Headers里的注解配置
            String cacheControl = request.cacheControl().toString();
            //没有网络并且添加了注解,才使用缓存.
            if (!InterNetUtil.isnetwork()&&!TextUtils.isEmpty(cacheControl)){
                //重置请求体;
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

         //如果没有添加注解,则不缓存
            if (TextUtils.isEmpty(cacheControl) || "no-store" .contains(cacheControl)) {
                //响应头设置成无缓存
                cacheControl = "no-store";
            } else if (InterNetUtil.isnetwork()) {
                //如果有网络,则将缓存的过期事件,设置为0,获取最新数据
                cacheControl = "public, max-age=" + 0;
            }else {
                //...如果无网络,则根据@headers注解的设置进行缓存.
            }
            Response response = chain.proceed(request);
            XLog.i("httpInterceptor", cacheControl);
            return response.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build();
        };
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .addNetworkInterceptor(cacheInterceptor)
                .addInterceptor(cacheInterceptor)
                .addInterceptor(getHeaderInterceptor())
                .cache(new Cache(MyApplication.getInstance().getCacheDir(), 10240 * 1024))
                .build();
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(Constant.HOST_INTERFACE)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(Double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(Long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(Float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(String.class, new StringNullAdapter())
                        .create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

    }
    /**
     * 设置Header
     *
     * @return
     */
    private static Interceptor getHeaderInterceptor() {
        return chain -> {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder()
                    //添加Token
                    .header("user", MemeryCatch.token)
                    .header("notes-questionType", "multipart/form-data");
            Request request = requestBuilder.build();
            return chain.proceed(request);
        };

    }
    private static class Instanace {
        private static final Retrofit retrofit = getInstanace();
    }
 }